<script lang="ts" setup>
import XtForm from '../form/XtForm.vue';
import { ref, reactive, computed, watch, toRaw, onMounted } from 'vue';
import {
  ElMessage,
  type UploadInstance,
  type UploadProps,
  type UploadRawFile,
  type FormInstance,
  type FormRules,
} from 'element-plus';
// 定义类型
interface FormItemOption {
  value?: string | number | boolean;
  label?: string;
  [key: string]: any;
}

interface FormItem {
  type: string;
  name: string;
  label: string;
  placeholder?: string;
  defaultValue?: any;
  options?: FormItemOption[];
  [key: string]: any;
}

interface FormMenuButton {
  label: string;
  action: string;
  type?: string;
  icon?: string;
  loading?: boolean;
  disabled?: boolean;
}

interface FormMenu {
  show?: boolean;
  width?: number;
  options: FormMenuButton[];
  direction?: boolean;
}

interface Props {
  modelValue: Record<string, any>;
  items: FormItem[];
  bars?: FormMenu;
  menuConfig?: FormMenu;
  fun?: () => void;
  labelWidth?: string;
  gutter?: number;
  clearable?: boolean;
  showDivider?: boolean;
  rules?: FormRules;
  config?: any[];
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({}),
  items: () => [],
  bars: () => ({ show: true, options: [], direction: true }),
  fun: () => () => {},
  labelWidth: '100px',
  clearable: true,
  showDivider: true,
  rules: () => [],
  config: () => [],
});

const emit = defineEmits([
  'update:modelValue',
  'submit',
  'reset',
  'event',
  'button-click',
]);

const formRef = ref<FormInstance | null>(null);
const formData = reactive<Record<string, any>>({ ...props.modelValue });

// 监听外部数据变化
watch(
  () => props.modelValue,
  (newVal) => {
    Object.assign(formData, newVal);
  },
  { deep: true }
);

// 监听内部数据变化
watch(
  formData,
  (newVal) => {
    emit('update:modelValue', toRaw(newVal));
  },
  { deep: true }
);

const formItems = computed(() => {
  return props.items.map((item) => {
    return {
      ...item,
      span: formItems.span || 8,
    };
  });
});

// 操作按钮区域样式
const actionStyle = computed(() => {
  return {
    width: `${props.bars.width}px` || '',
  };
});

// 处理表单事件
const handleEvent = (type: string, item: FormItem) => {
  emit('event', type, item.name, formData[item.name], item);
};

// 处理操作按钮点击
const handleButtonAction = (action: string) => {
  if (action === 'reset') {
    resetForm();
    emit('reset');
  } else {
    validateForm().then((valid) => {
      if (valid) {
        emit('submit', toRaw(formData), action);
      }
    });
  }
};

// 表单验证
const validateForm = async (): Promise<boolean> => {
  if (!formRef.value) return true;

  try {
    await formRef.value.validate();
    return true;
  } catch (error) {
    ElMessage.warning('请检查表单填写是否正确');
    return false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 获取表单实例和数据
const getForm = () => {
  return {
    formRef: formRef.value,
    formData: toRaw(formData),
  };
};

// 暴露方法给父组件
defineExpose({
  validateForm,
  resetForm,
  getForm,
});

// 初始化表单数据
onMounted(() => {
  props.items.forEach((item) => {
    if (formData[item.name] === undefined) {
      if (item.type === 'checkbox') {
        formData[item.name] = [];
      } else {
        formData[item.name] =
          item.defaultValue !== undefined ? item.defaultValue : '';
      }
    }
  });
});
</script>

<template>
  <div class="xt-inline-form">
    <div class="inline-form-box">
      <!-- 使用封装的xt-form组件 -->
      <xt-form
        ref="formRef"
        class="form-content"
        v-model="formData"
        :items="formItems"
        :config="props.config"
        :rules="props.rules"
        :label-width="props.labelWidth"
        :gutter="24"
        @update:modelValue="emit('update:modelValue', $event)">
      </xt-form>
      <!-- 操作按钮区域 -->
      <div
        v-if="bars"
        class="form-actions"
        :class="{
          'actions-direction': bars.direction !== false,
        }"
        :style="actionStyle">
        <el-button
          v-for="(btn, btnIndex) in bars.options"
          :key="btnIndex"
          :type="btn.type || 'primary'"
          :icon="btn.icon"
          :loading="btn.loading"
          :disabled="btn.disabled"
          @click="handleButtonAction(btn.action)">
          {{ btn.label }}
        </el-button>
        <el-link
          v-if="bars.options.length > 6"
          >{{ bars.options.length > 6 ? '展开' : '收起' }}</el-link
        >
      </div>
    </div>
    <el-divider v-if="props.showDivider" />
  </div>
</template>

<style scoped>
.xt-inline-form {
  width: 100%;
}

.inline-form-box {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.form-content {
  flex: 1;
}
.form-actions {
  display: flex;
  flex-direction: column;
}

.actions-direction {
  border-left: 1px var(--el-border-color) var(--el-border-style);
  padding-left: 24px;
}

.el-divider--horizontal{
  margin: 0px;
}
.el-button + .el-button {
  margin-left: 0px;
  margin-top: 18px;
}

/* .action-divider {
  width: 1px;
  background-color: #dcdfe6;
  align-self: stretch;
  margin: 0 8px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
} */
</style>
